﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using VideoClassLibrary.BusinessLogicLayer;
using VideoClassLibrary.CacheManager;
using VideoClassLibrary.Extension;
using VideoClassLibrary.Model;

public partial class Manager_ClassCourseCalendar :AdminUserBase
{
    private int Id = 0;
    protected void Page_Load(object sender, EventArgs e)
    {

        if (Request["ID"] != null)
        {
            if (!StringUtils.IsNumeric(Request["ID"]))
            {
                JsHelper.AlertAndRedirect("参数非法，请联系管理员", "ViewTrainingClassList.aspx"); 
            }
            Id = Convert.ToInt32(Request["ID"]);
        }
        if (!IsPostBack)
        {

            this.caleyear.SelectedValue = DateTime.Today.Year.ToString();
            this.calemon.SelectedValue = DateTime.Today.Month.ToString();
            CreateCourseCalendar(int.Parse(caleyear.SelectedValue), int.Parse(calemon.SelectedValue));
            CreateWeekCourse(int.Parse(caleyear.SelectedValue), int.Parse(calemon.SelectedValue), DateTime.Now.Day);
            GetAllClass();
            GetClassById();
        }
    }
    public  void  GetClassById()
    {
        TrainClassModule tr = new TrainClassModule();
        V_TrainClass vTrainClass = tr.GetTrainClassModelById(Id);
        ltrClass.Text = vTrainClass.VTC_name;
    }

    public  void GetAllClass()
    {
        TrainClassModule tr=new TrainClassModule();
        DataSet dataSet=tr.GetTrainclassListByWhere(CurrentUser.SchoolID, "");
        repAllCity.DataSource = dataSet;
        repAllCity.DataBind();

    }


    private void CreateCourseCalendar(int currYear, int currMonth)
    {
        StringBuilder sbCalendarTemp = new StringBuilder();
        StringBuilder sbCourseTemp = new StringBuilder();//按课程分类的课表
        StringBuilder sbListTemp = new StringBuilder();//列表式课表
        int currDay = 1;
        DayOfWeek beginWeekDay = new DateTime(currYear, currMonth, 1).DayOfWeek;
        DayOfWeek endWeekDay = new DateTime(currYear, currMonth, DateTime.DaysInMonth(currYear, currMonth)).DayOfWeek;
        bool isStarted = false;
        CourseListModule service = new CourseListModule();
        DataSet UserCourseList = service.GetCourseByID(Id, CurrentUser.SchoolID, "", "");
        CommonCacheManager.FlushCache();
        CommonCacheManager.AddCacheData<DataSet>("CourseList",UserCourseList,60);



        #region 生成日历的html,使用table
        sbCalendarTemp.AppendLine(" <table  class=\"tableCourse\" >");
        sbCalendarTemp.AppendLine(" <tr> <th style=\"color:Red\">星期日</th><th>星期一</th><th>星期二</th><th>星期三</th><th>星期四</th><th>星期五</th><th style=\"color:Green\">星期六</th> </tr>");
        for (int i = 1; i <= 6; i++)
        {
            sbCalendarTemp.AppendLine("<tr> ");
            for (int j = 0; j < 7; j++)
            {
                if (currDay <= DateTime.DaysInMonth(currYear, currMonth))
                {
                    if ((DayOfWeek)Enum.Parse(typeof(DayOfWeek), j.ToString()) == beginWeekDay)
                    {
                        //sbTemp.AppendLine(" <li><p><span class=\"day_in_moth\"></span><span class=\"day\">" + currDay + "</span></p>");
                        sbCalendarTemp.AppendLine("  <td>");
                        sbCalendarTemp.AppendLine(GetInnerTableHtml(currYear, currMonth, currDay));
                        sbCalendarTemp.AppendLine("</td>");
                        isStarted = true;
                        currDay++;
                    }
                    else
                    {
                        if (isStarted == true)
                        {
                            sbCalendarTemp.AppendLine(" <td>");
                            sbCalendarTemp.AppendLine(GetInnerTableHtml(currYear, currMonth, currDay));
                            sbCalendarTemp.AppendLine("</td>");
                            currDay++;
                        }
                        else
                        {
                            sbCalendarTemp.AppendLine(" <td >&nbsp;</td>");
                        }

                    }
                }
                else
                {
                    sbCalendarTemp.AppendLine(" <td >&nbsp;</td>");
                }
            }
            sbCalendarTemp.AppendLine("</tr>");

        }
        sbCalendarTemp.AppendLine("</table>");


        #endregion
        tableCourseList.InnerHtml = sbCalendarTemp.ToString();

        #region 按课程分类的课表
        courseTable.InnerHtml = CreateCourseListHtml();
        #endregion

        #region 按课程分类的课表
        //mid_r05.InnerHtml=CreateCourseByWeekHtml();
        #endregion
    }
    protected void Calendar_SelectedIndexChanged(object sender, EventArgs e)
    {
        CreateCourseCalendar(int.Parse(caleyear.SelectedValue), int.Parse(calemon.SelectedValue));
        CreateWeekCourse(int.Parse(caleyear.SelectedValue), int.Parse(calemon.SelectedValue), 1);
    }
    /// <summary>
    /// 创建按课程分类的课程表
    /// </summary>
    /// <returns></returns>
    private string CreateCourseListHtml()
    {
        StringBuilder sbCourseList = new StringBuilder();
        StringBuilder sbTemp = null;
        //   DataSet UserCourseList = CommonCacheManager.GetCacheData<DataSet>("UserCourse" + MembershipService.GetUser().ID);

        CourseListModule service = new CourseListModule();
        DataSet UserCourseList = service.GetCourseByID(Id, CurrentUser.SchoolID, "", "");
        if (UserCourseList != null)
        {
            DataTable dData = UserCourseList.Tables[0];
            DataTable dtCourseId = dData.DefaultView.ToTable(true, new string[] { "ID" });
            int tempId = 0;
            string playJs = string.Empty;
            for (int i = 0; i < dtCourseId.Rows.Count; i++)
            {
                tempId = int.Parse(dtCourseId.Rows[i][0].ToString());
                DataRow[] drList = dData.Select("id=" + tempId);
                sbTemp = new StringBuilder();
                sbTemp.AppendLine(
                    "<div class=\"classform\"> <table border=\"0\" cellpadding=\"0\" cellspacing=\"1\">");

                for (int j = 0; j < drList.Length; j++)
                {
                    playJs = string.Format("VideoPlay('{0}','{1}','{2}','{3}','{4}')", drList[j]["ID"],
                                           DateTime.Parse(drList[j]["VCL_startDate"].ToString()).ToShortDateString(),
                                           drList[j]["RoomID"], drList[j]["VCL_startTime"], drList[j]["VCL_EndTime"]);
                    HidCourseDate.Value = DateTime.Parse(drList[j]["VCL_startDate"].ToString()).ToShortDateString();
                    HidRoomId.Value = drList[j]["RoomID"].ToString();

                    HidEndTime.Value = drList[j]["VCL_EndTime"].ToString();
                    HidStartTime.Value = drList[j]["VCL_startTime"].ToString();
                    sbTemp.AppendLine(
                        string.Format(
                            " <tr> <td class=\"formyangshi1\">{0}</td><td class=\"formyangshi2\">{1} {2}-{3}</td><td class=\"formyangshi3\" style=\"margin-left:5px;\">{4}培训班  教室：{5} {6}</td></tr>",
                            (j == 0 ? drList[j]["VC_name"] : ""),
                            DateTime.Parse(drList[j]["VCL_startDate"].ToString()).ToString("yyyy-MM-dd"),
                            DateTime.Parse(drList[j]["VCL_startTime"].ToString()).ToString("HH:mm"),
                            DateTime.Parse(drList[j]["VCL_EndTime"].ToString()).ToString("HH:mm"),
                            drList[j]["Vtc_name"],
                            drList[j]["VR_roomName"],
                            "<a href='javascript:' style=\" color:blue;\" onclick=\"" + playJs + "\">开始学习</a>"));
                }
                sbTemp.AppendLine("</table></div> <div class=\"classform1\"></div> ");
                sbCourseList.AppendLine(sbTemp.ToString());
            }
        }
        return sbCourseList.ToString();
    }

    /// <summary>
    /// 获取日历课程表中，包含课程信息的html
    /// </summary>
    /// <param name="currYear"></param>
    /// <param name="currMonth"></param>
    /// <param name="currDay"></param>
    /// <returns></returns>
    private string GetInnerTableHtml(int currYear, int currMonth, int currDay)
    {
        StringBuilder sbTemp = new StringBuilder();
        DateTime dtDate = new DateTime(currYear, currMonth, currDay);
        DataRow[] drCourseInfo = null;

        CourseListModule service = new CourseListModule();
        DataSet UserCourseList = service.GetCourseByID(Id, 1, "", "");
        //DataSet UserCourseList =
          //  CommonCacheManager.GetCacheData<DataSet>("UserCourse" + MembershipService.GetUser().ID);
        //if(UserCourseList==null)
        //{
        //    Response.Redirect(ResolveClientUrl("~/UserLogin.aspx")+"?ReturnUrl="+Request.Url);

        //}
        if (UserCourseList != null && UserCourseList.Tables[0].Rows.Count > 0)
        {

            drCourseInfo =
                UserCourseList.Tables[0].Select("VCL_startDate='" + dtDate.ToShortDateString() + "'",
                                                "VCL_startTime ");
        }

        StringBuilder sbTdAM = new StringBuilder();//上午课程
        StringBuilder sbTdPM = new StringBuilder();//下午课程
        sbTemp.Append(currDay);
        if (drCourseInfo != null)
        {
            if (drCourseInfo.Length > 0)
            {
                string courseInfo = string.Empty;
                string playJs = string.Empty;

                for (int k = 0; k < drCourseInfo.Length; k++)
                {
                    courseInfo = "课程：" + drCourseInfo[k]["VC_name"].ToString() + "   时间：" +
                                 DateTime.Parse(drCourseInfo[k]["VCL_startTime"].ToString()).ToString("HH:mm") + "-" +
                                 DateTime.Parse(drCourseInfo[k]["VCL_EndTime"].ToString()).ToString("HH:mm");
                    courseInfo += "    教室：" + drCourseInfo[k]["VR_roomName"].ToString();
                    playJs = string.Format("VideoPlay('{0}','{1}','{2}','{3}','{4}')", drCourseInfo[k]["ID"],
                                           dtDate.ToShortDateString(), drCourseInfo[k]["RoomID"],
                                           drCourseInfo[k]["VCL_startTime"], drCourseInfo[k]["VCL_EndTime"]);

                    if (DateTime.Parse(drCourseInfo[k]["VCL_startTime"].ToString()).Hour < 12)
                    {
                        sbTdAM.AppendLine("<a href='javascript:' onclick=\"" + playJs +
                                          "\" onmouseover=\"this.title ='" + courseInfo + "'\">" +
                                          StringUtils.getLimitLengthString(drCourseInfo[k]["VC_name"].ToString(), 8,
                                                                           "") + "</a><br/>");
                    }
                    else
                    {
                        sbTdPM.AppendLine("<a href='javascript:' onclick=\"" + playJs +
                                          "\" onmouseover=\"this.title ='" + courseInfo + "'\">" +
                                          StringUtils.getLimitLengthString(drCourseInfo[k]["VC_name"].ToString(), 8,
                                                                           "") + "</a><br/>");
                    }
                }
                sbTemp.AppendLine(
                    " <div class=\"courseNameTd\">");
                sbTemp.AppendLine("<li class='left'>" + sbTdAM + "</li> ");
                sbTemp.AppendLine("<li class='right'>" + sbTdPM + " </li></div>");
            }
        }
        return sbTemp.ToString();
    }
    //private  void GetCourse()
    //{
    //    DataSet dataSet = CommonCacheManager.GetCacheData<DataSet>("UserCourse" + MembershipService.GetUser().ID);


    //}

    private void CreateWeekCourse(int currYear, int currMonth, int currDay)
    {

        CourseWeek courseWeek = new CourseWeek();
        DateTime minTime = new DateTime();
        DateTime maxTime = new DateTime();
        DataSet dataSet = CommonCacheManager.GetCacheData<DataSet>("CourseList");
        CourseList.Text = courseWeek.GetCourseWeek(currYear, currMonth, currDay, 1, ref minTime, ref maxTime,dataSet);
        CurrentMinY.Value = minTime.Year.ToString();
        CurrentMinMon.Value = minTime.Month.ToString();
        CurrentMinDay.Value = minTime.Day.ToString();
        CurrentMaxY.Value = maxTime.Year.ToString();
        CurrentMaxMon.Value = maxTime.Month.ToString();
        CurrentMaxDay.Value = maxTime.Day.ToString();






    }
    
}
